package com.qingxin.sys.action;

import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.qingxin.sys.support.UploadFile;
import com.qingxin.sys.utils.UploadUtil;

/**
 * 上传处理
 * @author Administrator
 *
 */
@Controller
public class UploadAction extends BaseAction {

	
	/**
	 * 上传文件
	 * @param uploadFile
	 * @param thumb
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/myupload.json", method = RequestMethod.POST)
	@ResponseBody
	public Object myupload(MultipartFile uploadFile, String thumb, HttpServletRequest request) throws Exception {
		//原始文件名
		String origName = uploadFile.getOriginalFilename();
		//扩展名
		String ext = FilenameUtils.getExtension(origName).toLowerCase(Locale.ENGLISH);
		//保存目录
		String dir = UploadFile.getSaveDirByKey(UploadFile.DIR_TMPDIR);
		
		//文件保存名称
		String filename = UploadUtil.generateDirFilename();
		String fileSaveName = filename +"." + ext;
		
		String realPath = UploadFile.getFilerootRealpath(dir+"/"+fileSaveName);
		//目标文件对象
		File dest = new File(realPath);
		UploadUtil.checkDirAndCreate(dest.getParentFile());
		//保存文件
		uploadFile.transferTo(dest);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("fileName", fileSaveName);//保存到数据库中的值
		map.put("origName", origName);
		map.put("fileUrl", UploadFile.getFileUrl(dir+"/"+fileSaveName));
		map.put("fileSize", dest.length());
		map.put("code", 200);
		
		return map;
	}
	
}
